package com.jason;

public class DeadLock {

    /**
     * 资源1
     */
    private Object obj1 = new Object();

    /**
     * 资源2
     */
    private Object obj2 = new Object();


    public void method1() {
        String name = Thread.currentThread().getName();
        synchronized (obj1) {
            System.out.println(name + "获取到资源1");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (obj2) {
                System.out.println(name + "获取到资源2");
            }
            System.out.println(name + "释放资源2");
        }
        System.out.println(name + "释放资源1");
    }

    public void method2() {
        String name = Thread.currentThread().getName();
        synchronized (obj2) {
            System.out.println(name + "获取到资源2");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (obj1) {
                System.out.println(name + "获取到资源1");
            }
            System.out.println(name + "释放资源1");
        }
        System.out.println(name + "释放资源2");
    }

    public static void main(String[] args) {
        DeadLock deadLock = new DeadLock();
        Thread thread1 = new Thread(() -> {
            deadLock.method1();
        });

        Thread thread2 = new Thread(() -> {
            deadLock.method2();
        });
        thread1.start();
        thread2.start();
    }
}
